<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title></title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
	<select id="province">
		<option value="">请选择省</option>
	</select>

	<select id="city">
		<option value="">请选择市</option>
	</select>

	<select id="district">
		<option value="">请选择区/县</option>
	</select>
	<script>
		$(document).ready(function () {

			// $.getJSON(url,data,success)
			$.getJSON("./json/省市区.json", function (data) {
				console.log(data);
				// 如何获取一个省份信息
				let sheng = data[0]
				console.log(sheng);
				// 如何获取一个市的信息
				console.log(data["0,510000"]);
				// 获取区县级信息
				console.log(data["0,510000,510500"]);
				let shengId = Object.keys(sheng)
				let shengName = Object.values(sheng)
				console.log(shengName);
				let options = null;
				for (let i = 0; i < shengName.length; i++) {
					options += "<option value='" + shengId[i] + "'>" + shengName[i] + "</option>"
				}
				$("#province").append(options);


				// 如何获取对应的市
				$("#province").change(function () {
					let shengId = $(this).val();//获取省份的id
					if (shengId) {
						$("#city").empty().append(" <option>请选择市</option>");
						$("#district").empty().append(" <option>请选择区县</option>")
						console.log(shengId);
						let shiKey = "0," + shengId;
						let shiObj = data[shiKey];
						console.log(shiObj);
						let shiId = Object.keys(shiObj);
						let shiName = Object.values(shiObj);
						let shioptions = null;
						for (let i = 0; i < shiId.length; i++) {
							shioptions += "<option value='" + shiId[i] + "'>" + shiName[i] + "</option>"
						}
						$("#city").append(shioptions);
					}else{
						// 如果省不存在，也需要清空对应的市和区
						$("#city").empty().append(" <option>请选择市</option>");
						$("#district").empty().append(" <option>请选择区县</option>")
					}

				})
				// 如何获取对应的区县
				$("#city").change(function () {
					let shengId = $("#province").val();//获取省份的id
					let shiId = $(this).val();
					console.log(shengId);
					let quKey = "0," + shengId + "," + shiId;
					let quObj = data[quKey];
					console.log(quObj);
					let quId = Object.keys(quObj);
					let quName = Object.values(quObj);
					let quoptions = null;
					for (let i = 0; i < quId.length; i++) {
						quoptions += "<option value='" + quId[i] + "'>" + quName[i] + "</option>"
					}
					$("#district").append(quoptions);
				})
			})


		})

	</script>

</body>

</html>